#!/bin/sh

# https://developer.android.com/ndk/guides/other_build_systems#autoconf

NDK=/opt/android-sdk-update-manager/ndk/20.0.5594570
HOST_TAG=linux-x86_64
ABI=
TRIPLE=
BIN_TRIPLE=
API=

case $1 in
    arm32)
	ABI="armeabi-v7a"
	TRIPLE="armv7a-linux-androideabi"
	BIN_TRIPLE="arm-linux-androideabi"
	API=16
	;;
    arm64)
	ABI="arm64-v8a"
	TRIPLE="aarch64-linux-android"
	BIN_TRIPLE=${TRIPLE}
	API=21
	;;
    x86)
	ABI="x86"
	TRIPLE="i686-linux-android"
	BIN_TRIPLE=${TRIPLE}
	API=16
	;;
    x86_64)
	ABI="x86-64"
	TRIPLE="x86_64-linux-android"
	BIN_TRIPLE=${TRIPLE}
	API=21
	;;
    *)
	echo "Usage: $0 <arm32|arm64|x86|x86_64>"
	exit 1
	;;
esac

if [ -z "$2" ]; then
    WORK_DIR=$(pwd)
else
    WORK_DIR=$(cd $2; pwd)
fi

export TOOLCHAIN=$NDK/toolchains/llvm/prebuilt/$HOST_TAG
export CC=$TOOLCHAIN/bin/${TRIPLE}${API}-clang
export CXX=$TOOLCHAIN/bin/${TRIPLE}${API}-clang++
export AR=$TOOLCHAIN/bin/${BIN_TRIPLE}-ar
export AS=$TOOLCHAIN/bin/${BIN_TRIPLE}-as
export LD=$TOOLCHAIN/bin/${BIN_TRIPLE}-ld
export RANLIB=$TOOLCHAIN/bin/${BIN_TRIPLE}-ranlib
export STRIP=$TOOLCHAIN/bin/${BIN_TRIPLE}-strip

echo ""
echo "---------"
echo "WORK_DIR:  ${WORK_DIR}"
echo "---------"
echo "ABI     :  ${ABI}"
echo "---------"
echo "Triple  :  ${TRIPLE}"
echo "---------"
echo "BTriple  :  ${BIN_TRIPLE}"
echo "---------"
echo "AR      :  ${AR}"
echo "---------"
echo "AS      :  ${AS}"
echo "---------"
echo "CC      :  ${CC}"
echo "---------"
echo "CXX     :  ${CXX}"
echo "---------"
echo "LD      :  ${LD}"
echo "---------"
echo "RANLIB  :  ${RANLIB}"
echo "---------"
echo "STRIP   :  ${STRIP}"
echo "---------"
echo ""

${WORK_DIR}/configure --host ${TRIPLE} --prefix $(pwd)/install ${3} && make -j7 && make install
